package cn.iocoder.yudao.module.system.service.examclass;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.examclass.vo.*;
import cn.iocoder.yudao.module.system.controller.admin.examclass.vo.TeacherAccountExportExcelVO;
import cn.iocoder.yudao.module.system.convert.examclass.ExamClassConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.examclass.ExamClassDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.examclass.ExamClassMapper;
import cn.iocoder.yudao.module.system.dal.mysql.examclass.ExamClassStudentMapper;
import cn.iocoder.yudao.module.system.service.examclass.ExamClassService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 班级信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class ExamClassServiceImpl implements ExamClassService {

    @Resource
    private ExamClassMapper examClassMapper;
    
    @Resource
    private ExamClassStudentMapper examClassStudentMapper;
    
    @Resource
    private AdminUserService adminUserService;
    
    @Resource
    private PermissionService permissionService;

    @Resource
    private DeptService deptService;

    @Override
    public Long createExamClass(ExamClassCreateReqVO createReqVO) {
        // 校验班级编码唯一性
        validateClassCodeUnique(null, createReqVO.getClassCode());
        
        // 插入
        ExamClassDO examClass = ExamClassConvert.INSTANCE.convert(createReqVO);
        examClass.setStudentCount(0); // 初始学生人数为0
        
        // 设置当前登录用户的部门ID（用于数据权限控制）
        Long currentUserDeptId = SecurityFrameworkUtils.getLoginUserDeptId();
        if (currentUserDeptId != null) {
            examClass.setDeptId(currentUserDeptId);
            log.debug("设置班级部门ID: {}, 班级: {}", currentUserDeptId, createReqVO.getClassName());
        } else {
            log.warn("当前登录用户未设置部门ID，班级将不设置部门信息: {}", createReqVO.getClassName());
        }
        
        examClassMapper.insert(examClass);
        
        // 返回
        return examClass.getId();
    }

    @Override
    public void updateExamClass(ExamClassUpdateReqVO updateReqVO) {
        // 校验存在
        validateExamClassExists(updateReqVO.getId());
        // 校验班级编码唯一性
        validateClassCodeUnique(updateReqVO.getId(), updateReqVO.getClassCode());
        
        // 更新
        ExamClassDO updateObj = ExamClassConvert.INSTANCE.convert(updateReqVO);
        examClassMapper.updateById(updateObj);
    }

    @Override
    public void deleteExamClass(Long id) {
        // 校验存在
        validateExamClassExists(id);
        
        // 校验是否有学生
        Long studentCount = examClassStudentMapper.selectCountByClassId(id);
        if (studentCount > 0) {
            throw exception(EXAM_CLASS_HAS_STUDENTS);
        }
        
        // 删除
        examClassMapper.deleteById(id);
    }

    private void validateExamClassExists(Long id) {
        if (examClassMapper.selectById(id) == null) {
            throw exception(EXAM_CLASS_NOT_EXISTS);
        }
    }

    private void validateClassCodeUnique(Long id, String classCode) {
        ExamClassDO examClass = examClassMapper.selectByClassCode(classCode);
        if (examClass == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的班级
        if (id == null) {
            throw exception(EXAM_CLASS_CODE_DUPLICATE);
        }
        if (!examClass.getId().equals(id)) {
            throw exception(EXAM_CLASS_CODE_DUPLICATE);
        }
    }

    @Override
    public ExamClassDO getExamClass(Long id) {
        return examClassMapper.selectById(id);
    }

    @Override
    public List<ExamClassDO> getExamClassList(Collection<Long> ids) {
        return examClassMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<ExamClassDO> getExamClassPage(ExamClassPageReqVO pageReqVO) {
        return examClassMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ExamClassDO> getExamClassList(ExamClassPageReqVO exportReqVO) {
        return examClassMapper.selectList(exportReqVO);
    }

    @Override
    public ExamClassDO getExamClassByClassCode(String classCode) {
        return examClassMapper.selectByClassCode(classCode);
    }

    @Override
    public List<ExamClassDO> getExamClassListByTeacherId(Long teacherId) {
        // 检查用户是否具有校领导角色
        if (permissionService.hasAnyRoles(teacherId, "school_admin")) {
            // 如果是校领导，获取用户信息
            AdminUserDO user = adminUserService.getUser(teacherId);
            if (user != null && user.getDeptId() != null) {
                // 获取当前用户部门及所有子部门的ID集合
                Set<Long> deptIds = deptService.getChildDeptIdListFromCache(user.getDeptId());
                deptIds.add(user.getDeptId()); // 包含自身部门
                
                // 查询这些部门下的所有班级
                return examClassMapper.selectListByDeptIds(deptIds);
            }
            // 如果没有部门信息，返回空列表
            return Collections.emptyList();
        }
        // 否则返回该教师的班级
        return examClassMapper.selectListByTeacherId(teacherId);
    }

    @Override
    public List<ExamClassDO> getExamClassListByGrade(String grade) {
        return examClassMapper.selectListByGrade(grade);
    }

    @Override
    public List<TeacherAccountExportExcelVO> getTeacherAccountsForExport(ExamClassPageReqVO exportReqVO) {
        // 获取班级列表
        List<ExamClassDO> classList = examClassMapper.selectList(exportReqVO);
        
        List<TeacherAccountExportExcelVO> result = new ArrayList<>();
        for (ExamClassDO examClass : classList) {
            // 获取班主任用户信息
            AdminUserDO teacher = adminUserService.getUser(examClass.getTeacherId());
            if (teacher != null) {
                TeacherAccountExportExcelVO exportVO = TeacherAccountExportExcelVO.builder()
                    .userId(teacher.getId())
                    .username(teacher.getUsername())
                    .nickname(teacher.getNickname())
                    .classId(examClass.getId())
                    .className(examClass.getClassName())
                    .classCode(examClass.getClassCode())
                    .grade(examClass.getGrade())
                    .initialPassword("88888888") // 默认初始密码
                    .mobile(teacher.getMobile())
                    .email(teacher.getEmail())
                    .status(teacher.getStatus() == 0 ? "正常" : "停用")
                    .createTime(teacher.getCreateTime())
                    .remark(teacher.getRemark())
                    .build();
                result.add(exportVO);
            }
        }
        
        return result;
    }

    @Override
    public void updateStudentCount(Long classId) {
        Long count = examClassStudentMapper.selectCountByClassId(classId);
        ExamClassDO updateObj = new ExamClassDO();
        updateObj.setId(classId);
        updateObj.setStudentCount(count.intValue());
        examClassMapper.updateById(updateObj);
    }

}